package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.pactera.madp.cp.api.dto.track.BehaviorTrackDto;
import com.pactera.madp.cp.api.entity.BehaviorTrackEntity;
import com.pactera.madp.cp.api.entity.employeeWechat.EmployeeDoEntity;
import com.pactera.madp.cp.common.constant.BehaviorTrackFormatConst;
import com.pactera.madp.cp.service.EmployeeDoService;
import com.pactera.madp.cp.service.IWorkContactService;
import com.pactera.madp.cp.service.IWorkEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class BehaviorTrackTodoServiceImpl extends BaseBehaviorTrackServer {

    @Autowired
    private EmployeeDoService employeeDoService;

    @Override
    public void handleEvent(BehaviorTrackDto dto, IWorkEmployeeService workEmployeeService,
                            IWorkContactService workContactService, HttpServletResponse response) throws Exception{

        EmployeeDoEntity employeeDoEntity = employeeDoService.getById(dto.getTodoId());
        log.info("employeeDoEntity:{}",employeeDoEntity);
        log.info("behaviorTrackDto:{}",dto);
        if (employeeDoEntity == null || employeeDoEntity.getDoState().equals(1)) {
            //若代办提醒状态为已办/已删除，则不发送提醒消息
            return;
        }

        //参数校验
        vildateParams(dto);
        //事件处理
        BehaviorTrackEntity entity = new BehaviorTrackEntity();
        BeanUtil.copyProperties(dto, entity);
        baseHandleEvent(entity, workEmployeeService, workContactService, this, response);
    }

    /**
     * 参数校验
     * @param dto
     */
    private void vildateParams(BehaviorTrackDto dto) {
        if (StrUtil.isEmpty(dto.getContent())) {
            throw new IllegalArgumentException("提醒内容不能为空");
        }

    }

    /**
     * 业务数据组装
     * @param entity
     * @return
     */
    @Override
    protected String buildData(BehaviorTrackEntity entity){
        List<String> datas = new ArrayList<>();
        datas.add(entity.getUsername());
        datas.add(entity.getExternalUsername());
        datas.add(entity.getWxUserId());
        String content = String.format(BehaviorTrackFormatConst.TodoFormat, datas.toArray(new String[datas.size()]));

        return content;
    }
}
